package it.antonio.ilpizze.db.core.perst;

import it.antonio.ilpizze.db.index.utils.FPerst;
import it.antonio.ilpizze.db.io.IOFile;
import it.antonio.ilpizze.db.security.Role;
import it.antonio.ilpizze.db.security.User;

public class UserPerst implements FPerst<User> {
		
		private static final byte ADMIN = 15, READ = 16, READ_AND_WRITE = 17;
		
		@Override
		public long space() {
			return 100;
		}

		@Override
		public void persist(IOFile file, User user) {
			long toIncrement = file.position() + 100;
			if(user != null){
				if(user.name().length() + user.password().length() >= 95) throw new IllegalArgumentException("String too long");
				file.writeBoolean(false);
				file.writeString(user.name());
				file.writeString(user.password());
				switch (user.role()) {
					case ADMIN: file.writeByte(ADMIN); break;
					case READ_ONLY: file.writeByte(READ); break;
					case READ_AND_WRITE: file.writeByte(READ_AND_WRITE); break;
					default: break;
				}
			} else {
				file.writeBoolean(true);
			}
			file.position(toIncrement - 1);
			file.writeBoolean(true);
		}

		@Override
		public User read(IOFile file) {
			boolean isNull = file.readBoolean();
			if(isNull){
				return null;
			} else {
				String name = file.readString();
				String password = file.readString();
				Role role = null;
				switch (file.readByte()) {
					case ADMIN: role = Role.ADMIN; break;
					case READ: role = Role.READ_ONLY; break;
					case READ_AND_WRITE: role = Role.READ_AND_WRITE; break;
				}
				return new User(name, password, role);	
			}
		}
		
		
	}
